﻿using ARchGL.Declaration.Platform.Domain.Entities;
using ARchGL.Declaration.Platform.Domain.Events;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Net;
using TDF.Core.Configuration;
using TDF.Core.Event;
using TDF.Core.Ioc;
using TDF.Core.Log;

namespace ARchGL.Declaration.Platform.Service.EventHandles
{
    /// <summary>
    /// 项目文件推送
    /// 有新增的验收记录时通过此接口将数据推送到智慧工地系统。
    /// </summary>
    public class ProjectUploadFileHandle : IConsumer<ProjectUploadFileEvent>
    {
        /// <summary>
        /// 项目文件推送
        /// </summary>
        /// <param name="eventEntity"></param>
        public void Handler(ProjectUploadFileEvent eventEntity)
        {
            var configs = new Configs();
            var site = configs.GetValue("SiteUrl");
            if (!site.Contains("au.typeo.org")) return;

            var url = "api/open/v2/quality/acceptance/record";
            var json = string.Empty;
            var status = PushStatus.成功;
            var message = string.Empty;
            try
            {
                if (eventEntity == null) LogFactory.GetLogger().Info($"项目文件推送失败-没有获取到数据");
                //var filePath = site + "/" + configs.GetValue("VirtualDirectory") + eventEntity.fileUrl;
                var postdata = new
                {
                    eventEntity.projectCode,
                    eventEntity.partCode,
                    eventEntity.docTypeCode,
                    eventEntity.docNo,
                    eventEntity.docName,
                    eventEntity.fileUrl,
                    recordTime = eventEntity.recordTime.ToString("yyyy-MM-dd HH:mm:ss")
                };

                var request = new RestRequest(url, Method.POST);
                json = request.JsonSerializer.Serialize(postdata);
                var responsePost = BaseMethod.ExecuteRequest(request, json);
                message = responsePost.Content;
                if (responsePost.StatusCode != HttpStatusCode.OK)
                {
                    status = PushStatus.失败;
                    LogFactory.GetLogger().Info($"项目文件推送【失败】：{eventEntity.projectCode}-{eventEntity.partCode} | {message}");
                }
                else
                {
                    LogFactory.GetLogger().Info($"项目文件推送成功：{eventEntity.projectCode}-{eventEntity.partCode} | {message}");
                }
            }
            catch (Exception ex)
            {
                status = PushStatus.失败;
                message = ex.Message;
                LogFactory.GetLogger().Error($"项目文件推送【异常】：", ex);
            }

            //记录发送数据
            Ioc.Resolve<IPushService>().Save(new Push_Project_History
            {
                Url = url,
                Data = json,
                Message = message,
                Status = status,
                Type = PushType.验收记录,
            });
        }
    }
}
